from machine import I2C, Pin
import time

# LCD 常量定义
LCD_ADDRESS = 0x27  # I2C 地址（可能是 0x3F，具体根据你的屏幕）
LCD_WIDTH = 16      # 每行字符数
LCD_CHR = 1         # 发送数据
LCD_CMD = 0         # 发送命令

# LCD 命令
LCD_LINE_1 = 0x80   # 第一行起始地址
LCD_LINE_2 = 0xC0   # 第二行起始地址
LCD_BACKLIGHT = 0x08  # 背光开
ENABLE = 0b00000100  # Enable bit

# 初始化 I2C
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)

def lcd_write(byte, mode):
    """发送命令或数据到 LCD"""
    bits_high = mode | (byte & 0xF0) | LCD_BACKLIGHT
    bits_low = mode | ((byte << 4) & 0xF0) | LCD_BACKLIGHT
    i2c.writeto(LCD_ADDRESS, bytearray([bits_high, bits_high | ENABLE, bits_high & ~ENABLE]))
    i2c.writeto(LCD_ADDRESS, bytearray([bits_low, bits_low | ENABLE, bits_low & ~ENABLE]))
    time.sleep_us(50)

def lcd_init():
    """初始化 LCD 屏幕"""
    lcd_write(0x33, LCD_CMD)  # 初始化
    lcd_write(0x32, LCD_CMD)  # 设置为 4 位模式
    lcd_write(0x06, LCD_CMD)  # 光标移动方向
    lcd_write(0x0C, LCD_CMD)  # 打开显示，不显示光标
    lcd_write(0x28, LCD_CMD)  # 2 行模式
    lcd_write(0x01, LCD_CMD)  # 清屏
    time.sleep(5)

def lcd_clear():
    """清除 LCD 屏幕"""
    lcd_write(0x01, LCD_CMD)
    time.sleep(5)

def lcd_message(message, line):
    """在指定行显示消息"""
    if line == 1:
        lcd_write(LCD_LINE_1, LCD_CMD)
    elif line == 2:
        lcd_write(LCD_LINE_2, LCD_CMD)

    for char in message:
        lcd_write(ord(char), LCD_CHR)

# 初始化 LCD 并显示消息
lcd_init()
lcd_clear()

lcd_message("hello", 1)  # 第一行显示 "hello"
lcd_message("world", 2)  # 第二行显示 "world"
